package com.huawei.experiencereuse.utils;

import android.content.res.AssetManager;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ModelUtility {
    private static final String TAG = ModelUtility.class.getSimpleName();

    private static void releaseResource(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean isResourcesExist(String modelName, String appDir) {
        File dir = new File(appDir);
        File[] files = dir.listFiles();
        if (files == null) {
            return false;
        }
        for (File file : files) {
            if (file.getName().equals(modelName)) {
                return true;
            }
        }
        return false;
    }

    public static boolean copyResourcesToAppDir(AssetManager am, String amSrcDirRelative, String destDir, String fileName) {
        File destFile = new File(destDir, fileName);
        if (!destFile.getParentFile().exists()) {
            if (!destFile.getParentFile().mkdirs()) {
                return false;
            }
        }

        InputStream fileInput = null;
        FileOutputStream fileOutput = null;
        try {
            fileInput = am.open(amSrcDirRelative + fileName);
            fileOutput = new FileOutputStream(destFile);
            byte[] buffer = new byte[4096];
            int len;
            while ((len = fileInput.read(buffer)) != -1) {
                fileOutput.write(buffer, 0, len);
            }
            return true;
        } catch (IOException exception) {
            return false;
        } finally {
            releaseResource(fileOutput);
            releaseResource(fileInput);
        }
    }
}
